package com.task.scheduling.controller;

import com.alibaba.fastjson.JSONObject;
import com.task.scheduling.enums.ServiceType;
import com.task.scheduling.enums.TaskStatus;
import com.task.scheduling.enums.ThirdParty;
import com.task.scheduling.model.TaskSchedulingModel;
import com.task.scheduling.model.UpdateTairTaskData;
import com.task.scheduling.processor.ProcessorTypes;
import com.task.scheduling.service.DispatcherHolder;
import com.task.scheduling.service.FutureHolder;
import com.task.scheduling.service.TaskSchedulingService;
import com.task.scheduling.util.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.Future;

@Controller
@RequestMapping("/task")
public class TaskController {

	private Logger log = LoggerFactory.getLogger(TaskController.class);

	@Resource
	private TaskSchedulingService taskSchedulingService;

	@Value("${server.port}")
	private String port;

	/**
	 * 成功kill了返回1
	 * 否则返回0
	 * id不存在返回-1
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/kill")
	@ResponseBody
	public String killTask(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");

		if(StringUtils.isEmpty(id)) {
			return "-1";
		}

		Future<?> future = FutureHolder.getFuture(Long.valueOf(id));
		if(future != null) {
			if(future.isCancelled()) {
				return "1";
			}
			boolean flag = future.cancel(true);
			if(flag) {
				return "1";
			}
			return "0";
		} else {
			TaskSchedulingModel model = taskSchedulingService.selectById(Long.valueOf(id));
			if(model == null) {
				return "-1";
			}
			if(model.getTaskStatus() == TaskStatus.SUCCESS.getCode() ||
					model.getTaskStatus() == TaskStatus.INTERRUPTED.getCode() ||
					model.getTaskStatus() == TaskStatus.FAIL.getCode()) {
				return "1";
			}
			String result = HttpClientUtil.sendGet("http://" + model.getExecutor() + ":" + port + "/start/dispatcher", Collections.EMPTY_MAP, Collections.EMPTY_MAP, "utf-8");
			if(StringUtils.isEmpty(result)) {
				return "-1";
			}
			return result;
		}
	}

	@RequestMapping("/kill/direct")
	@ResponseBody
	public String killDirect(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");

		if(StringUtils.isEmpty(id)) {
			return "-1";
		}

		Future<?> future = FutureHolder.getFuture(Long.valueOf(id));

		if(future != null) {
			boolean flag = future.cancel(true);
			if(flag) {
				return "1";
			}
			return "0";
		}
		return "-1";
	}


	/**
	 * dispatcher
	 *    开启状态 1
	 *    停止状态 0
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/start/dispatcher")
	@ResponseBody
	public String startDispatcher(HttpServletRequest request, HttpServletResponse response) {
		boolean status = DispatcherHolder.getDispatcherStatus();
		if(status == Boolean.TRUE) {
			return "1";
		} else {
			DispatcherHolder.startDispatcher();
			return DispatcherHolder.getDispatcherStatus() == Boolean.TRUE ? "1" : "0";
		}
	}

	/**
	 * dispatcher
	 *      开启状态 1
	 *      停止状态 0
	 * 机器未能连接
	 *      -1
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/start/dispatcher/all")
	@ResponseBody
	public Map<String, String> startDispatcherAll(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map<String, String> map = new HashMap<>();
		String executor = "";
		String result = null;
		try {
			List<String> executors = taskSchedulingService.getAllExecutors();
			for(int i=0; i<executors.size(); i++) {
				executor = executors.get(i);
				result = HttpClientUtil.sendGet("http://" + executor + ":" + port + "/start/dispatcher", Collections.EMPTY_MAP, Collections.EMPTY_MAP, "utf-8");
				if (StringUtils.isEmpty(result)) {
					map.put(executor, "-1");
					continue;
				}
				map.put(executor, result);
			}
			return map;
		} catch (Exception e) {
			log.error("TaskController /start/dispatcher/all error" + e.getMessage(), e);
			map.put(executor, "-2");
			return map;
		}
	}

	/**
	 * dispatcher
	 *     开启状态 1
	 *     停止状态 0
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/stop/dispatcher")
	@ResponseBody
	public String stopDispatcher(HttpServletRequest request, HttpServletResponse response) {
		boolean status = DispatcherHolder.getDispatcherStatus();
		if(status == Boolean.FALSE) {
			return "0";
		} else {
			DispatcherHolder.stopDispatcher();
			return DispatcherHolder.getDispatcherStatus() == Boolean.TRUE ? "1" : "0";
		}
	}

	@RequestMapping("/stop/dispatcher/all")
	@ResponseBody
	public Map<String, String> stopDispatcherAll(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map<String, String> map = new HashMap<>();
		String executor = "";
		String result = null;
		try {
			List<String> executors = taskSchedulingService.getAllExecutors();
			for(int i=0; i<executors.size(); i++) {
				executor = executors.get(i);
				result = HttpClientUtil.sendGet("http://" + executor + ":" + port + "/stop/dispatcher", Collections.EMPTY_MAP, Collections.EMPTY_MAP, "utf-8");
				if(StringUtils.isEmpty(result)) {
					map.put(executor, "-1");
					continue;
				}
				map.put(executor, result);
			}
			return map;
		} catch (Exception e) {
			log.error("TaskController /stop/dispatcher/all error" + e.getMessage(), e);
			map.put(executor, "-2");
			return map;
		}
	}

	/**
	 * 添加任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/addTask")
	@ResponseBody
	public  TaskSchedulingModel addTask(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			String thirdParty = request.getParameter("");
			String serviceType = request.getParameter("");
			String beginTime = request.getParameter("");
			String endTime = request.getParameter("");
			String from = request.getParameter("from");
			String size = request.getParameter("size");

			UpdateTairTaskData td = new UpdateTairTaskData();
			td.setThirdParty(ThirdParty.gaode.toString());
			td.setServiceType(ServiceType.geo.toString());
			td.setParams("北京,东方明珠电视塔,王府井");
			td.setBeginTime(null);
			td.setEndTime(null);
			td.setFrom(0);
			td.setSize(4);



			TaskSchedulingModel model = new TaskSchedulingModel();
			model.setUuid(UUID.randomUUID().toString());
			model.setBizId(ProcessorTypes.UPDATE_TAIR.getType());
			model.setExecCount(0);
			model.setMaxExecCount(3);
			model.setTaskData(JSONObject.toJSONString(td));
			model.setTaskStatus(TaskStatus.NEW_TASK.getCode());
			model.setTaskType(ProcessorTypes.UPDATE_TAIR.getType());
			model.setTaskMessage("");
			model.setExecutor("none");
			model.setTimeCount(0);
			model.setExecutionTime(new Date());
			model.setDoTime(null);
			model.setCreateTime(new Date());
			model.setUpdateTime(new Date());

			System.out.println(taskSchedulingService.save(model));
			return model;
		} catch(Exception e) {
			return null;
		}
	}
	

	

	private Date getDate() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.SECOND, -100);
		return cal.getTime();
	}
}
